package bp.net;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class NeuroNerve extends Nerve {

	private List<Dendrite> dendrites;
	private double threshold;

	public NeuroNerve(NeuroLayer layer) {
		
		super(layer);
		this.dendrites = new ArrayList<Dendrite>();

		for (Object o : layer.getPreLayer().getNerves()) {
			Nerve n = (Nerve) o;
			double w = new Random().nextDouble() * 2.0 - 1.0;
			Dendrite d = new Dendrite(this, n, w);
			this.dendrites.add(d);
		}
	}

	public NeuroNerve(NeuroLayer layer, List<Double> list) {
		super(layer);
		this.dendrites = new ArrayList<Dendrite>();

		for (int i = 0;i<list.size();i++){		
			Nerve n = (Nerve) layer.getPreLayer().getNerves().get(i);
			Dendrite d = new Dendrite(this, n, list.get(i));
			this.dendrites.add(d);
		}
	}

	public void compute() {
		for(Dendrite d:this.dendrites)
			d.compute();
		this.setInput(this.calInput());
		double p = Math.pow(Math.E, 0 - this.getInput());
		this.output = 1.0 / (1.0 + p);
	}

	private double calInput() {
		double tmp = 0;
		for (Dendrite d : dendrites) {
			tmp += d.getSignal();
		}
		return tmp - this.threshold;
	}

	public List<Dendrite> getDendrites() {
		return dendrites;
	}

	public Dendrite getDendrite(int j) {
		return this.dendrites.get(j);
	}

	public List<Double> getWeights() {
		List<Double> list = new ArrayList<Double>();
		for(Dendrite d:this.dendrites){
			list.add(d.getWeight());
		}
		return list;
	}

	public void setWeights(List<Double> list) {
		for(int i=0;i<list.size();i++){
			this.dendrites.get(i).setWeight(list.get(i));
		}
	}
}
